#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include "cJSON.h"
#define N 64
typedef struct sockaddr SA;
int temp = 0;
void thread_func()
{
    printf("will recv new connect\n");
    int sockfd, clientfd;
    char buf[N];
    int addrlen = sizeof(struct sockaddr);
    struct sockaddr_in addr, clientaddr;
    int nbytes;
    // 1创建一个套接字--socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket err");
        exit(-1);
    }

    // 2定义套接字地址--sockaddr_in
    bzero(&addr, addrlen);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(8001);  //新的连接用8001端口

    // 3绑定套接字--bind
    if (bind(sockfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        exit(-1);
    }

    // 4启动监听--listen
    if (listen(sockfd, 5) < 0)
    {
        perror("listen err");
        exit(-1);
    }

    // 5接收连接--accept
    clientfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen);
    if (clientfd < 0)
    {
        perror("accept err");
        exit(-1);
    }

    printf("recv new client\n");

    // 6收发数据--recv/send
    while (1) {
            nbytes = recv(clientfd, buf, N, 0);
            if(nbytes < 0) {
                    perror("recv err");
                    exit(-1);
            } else if (nbytes > 0) {
                    printf("recv %s-%d data = %s\n", inet_ntoa(clientaddr.sin_addr), \
                            ntohs(clientaddr.sin_port), buf);
            } else {
                    printf("peer exit\n");
                    break;
            }
    }
    // memset(buffer, 0, sizeof(buffer));
    // int received_bytes3 = recv(client_socket, buffer, sizeof(buffer), 0);
    // if (received_bytes3 > 0)
    // {
    //     buffer[received_bytes3] = '\0';
    //     printf("Received JSON_Data: %s\n", buffer);
    // }
    // else
    // {
    //     printf("接受失败！ #3\n");
    // }
}
int main(int argc, char const *argv[])
{
    int broadfd;

    // 创建一个socket文件描述符
    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (broadfd < 0)
    {
        perror("sock err");
        return -1;
    }

    // 绑定套接字(ip+port)
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8888); // 端口号
    addr.sin_addr.s_addr = INADDR_ANY;

    int addrlen = sizeof(addr);

    if (bind(broadfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }
    ssize_t len;
    char buf[N] = {0};
    struct sockaddr_in cliaddr;

    // 接收"coffee"搜索包
    bzero(buf, N);
    len = recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&cliaddr, &addrlen);

    // 判断是否是本公司产品：收到的数据是否"coffee"
    if (strcmp(buf, "coffee") != 0)
    {
        printf("%s\n", buf);
        printf("not my coffee\n");
        return -1;
    }
    else
        // 回复yes，告诉软件，我收到了搜索协议，并且回复地址
        sendto(broadfd, "yes", 4, 0, (struct sockaddr *)&cliaddr, addrlen);
    
    // 变身为TCP服务器，准备接收软件的升级文件
    int tcpfd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcpfd < 0)
    {
        perror("sock err");
        return -1;
    }

    if (bind(tcpfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    // 监听套接字
    if (listen(tcpfd, 5) < 0)
    {
        perror("listen err");
        return -1;
    }

    // 接收客户端的连接
    printf("wait client connect\n");
    int clifd;

    // 接收对端的地址
    clifd = accept(tcpfd, NULL, NULL);
    if (clifd < 0)
    {
        perror("accept err");
        return -1;
    }
    printf("new cononect coming\n");
    int client_sock;
    char buffer[1024] = "0";
    while (1)
    {
        int received_bytes = recv(clifd, buffer, 1024, 0);
        if (received_bytes >= 0)
        {
            buffer[received_bytes] = '\0';
            printf("Received JSON: %s\n", buffer);
        }
        else
        {
            printf("err 1111\n");
        }
        cJSON *root = cJSON_Parse(buffer);
        cJSON *item = cJSON_GetObjectItem(root, "type");
        printf("%s:%d\n", item->string, item->valueint);

        if (item->valueint == 1)
        {
            cJSON *temp = cJSON_GetObjectItem(root, "data");
            if (temp == NULL)
            {
                temp = 0;
                cJSON_AddItemToObject(root, "result", cJSON_CreateNumber(0));
                cJSON_AddItemToObject(root, "up_config", cJSON_CreateBool(temp));
                char *json_str = cJSON_PrintUnformatted(root);
                // printf("测试数据：%ld\n",sizeof(*json_str));
                int received_bytes2 = send(clifd, json_str, strlen(json_str), 0);
                if (received_bytes > 0)
                {
                    printf("成功发送！\n");
                }
                else
                {
                    printf("发送失败！ #2\n");
                }
            }
            else
            {
                temp = 1;
                printf("已存在\n");
                cJSON_AddItemToObject(root, "result", cJSON_CreateNumber(0));
                cJSON_AddItemToObject(root, "up_config", cJSON_CreateBool(temp));
                char *json_str = cJSON_PrintUnformatted(root);
                // printf("测试数据：%ld\n",sizeof(*json_str));
                int received_bytes2 = send(clifd, json_str, strlen(json_str), 0);
                if (received_bytes > 0)
                {
                    printf("成功发送！\n");
                }
                else
                {
                    printf("发送失败！ #2\n");
                }
            }
        }
        else if (item->valueint == 2)
        {
            cJSON *data = cJSON_GetObjectItem(buffer, "data");
            cJSON *flag = cJSON_GetObjectItem(data, "flag");
            if (!strcmp(flag->string, "start"))
            {
                cJSON *file_name = cJSON_GetObjectItem(data, "file_name");
                cJSON *file_len = cJSON_GetObjectItem(data, "file_len");
                pthread_t tid;
                int ret;
                ret = pthread_create(&tid, NULL, thread_func, NULL);
                if (ret != 0)
                {
                    perror("pthread_create");
                    exit(EXIT_FAILURE);
                }
                // 等待线程结束
                pthread_join(tid, NULL);
            }
            else if (!strcmp(flag->string, "stop"))
            {
            }
        }
        else if (item->valueint == 3)
        {
        }
    }
    close(clifd);
    close(tcpfd);
    close(broadfd);
    return 0;
}